package org.amos.gateway.handler;

import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.cloud.sentinel.datasource.config.DataSourcePropertiesConfiguration;
import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.command.UpdateGatewayApiDefinitionGroupCommandHandler;
import com.alibaba.csp.sentinel.adapter.gateway.common.command.UpdateGatewayRuleCommandHandler;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Map;
import java.util.Set;

/**
 * @desc: 限流持久化nacos处理
 * @author: liubt
 * @date: 2020-12-19 13:52
 **/
public class SentinelPersistHandler implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private SentinelProperties sentinelProperties;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        initGateWayApiDefinition();
        initGatewayFlowRule();
    }

    private void initGatewayFlowRule() {
        //gw-rule
        NacosDataSourceProperties nacosProperty = getNacosDataSourceProperties("gw-rule");
        NacosWritableDataSource<Set<GatewayFlowRule>> nacosWritableDataSource
                = new NacosWritableDataSource(nacosProperty.getServerAddr()
                , nacosProperty.getGroupId(), nacosProperty.getDataId(), nacosProperty.getNamespace());
        //网关流控规则处理类
        UpdateGatewayRuleCommandHandler.setWritableDataSource(nacosWritableDataSource);
    }

    private NacosDataSourceProperties getNacosDataSourceProperties(String key) {
        Map<String, DataSourcePropertiesConfiguration> datasource = sentinelProperties.getDatasource();
        DataSourcePropertiesConfiguration configuration
                = datasource.get(key);
        NacosDataSourceProperties nacosProperty = configuration.getNacos();
        return nacosProperty;
    }

    private void initGateWayApiDefinition() {
        //gw-api-group
        NacosDataSourceProperties nacosProperty = getNacosDataSourceProperties("gw-api-group");
        NacosWritableDataSource<Set<ApiDefinition>> nacosWritableDataSource
                = new NacosWritableDataSource(nacosProperty.getServerAddr()
                , nacosProperty.getGroupId(), nacosProperty.getDataId(), nacosProperty.getNamespace());
                //更新处理类
                UpdateGatewayApiDefinitionGroupCommandHandler.setWritableDataSource(nacosWritableDataSource);
    }
}


